import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


public class MarshelUtil {

	public static void marshal(Object foo, OutputStream out) throws IOException {      
		try {
			JAXBContext jc = JAXBContext.newInstance(foo.getClass());
			Marshaller marshaller = jc.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(foo, out);
		}
		catch (JAXBException ex) {
			throw new IOException(ex);
		}
		finally {
//			out.close(); TODO close syso?!
		}
	}
	
	public static <T> T unmarshal(String xmlString, Class<T> type) throws IOException {
		InputStream in = new ByteArrayInputStream(xmlString.getBytes());
		return unmarshal(in, type);
	}

	// unsafe casting to T
	@SuppressWarnings("unchecked")
	public static <T> T unmarshal(InputStream in, Class<T> type) throws IOException {

		try {
			JAXBContext jc = JAXBContext.newInstance(type);
			Unmarshaller unmarshaller = jc.createUnmarshaller();

			try {				
				return (T)unmarshaller.unmarshal(in);
			} catch (Exception e) {
				return null;
			}
		}
		catch (JAXBException ex) {
			throw new IOException(ex);
		}
		finally {
			in.close();
		}
	}
}
